<template>
  <div v-if="cinemaInfo" style="margin-bottom: -49px; background: #fff">
    <van-nav-bar
      @click-left="handleBack"
      style="position: sticky; top: 0; z-index: 2"
    >
      <template #left>
        <van-icon
          name="arrow-left"
          color="#8A8B8C"
          size="24"
          style="position: sticky; top: 0; z-index: 2"
        />
      </template>
    </van-nav-bar>
    <div class="header-title" style="position: sticky; top: 0; z-index: 2">
      {{ cinemaInfo.name }}
    </div>
    <div>
      <div class="tags" @click="showPopup">
        <span
          class="tag"
          :class="i === cinemaInfo.services.length - 2 ? 'tag-1' : ''"
          v-for="(item, i) in cinemaInfo.services"
          :key="i"
          >{{ item.name }}</span
        >
        <van-icon name="arrow" />
      </div>
      <div class="address">
        <van-icon name="location-o" color="#A7AAAD" size="24" />
        <span>{{ cinemaInfo.address }}</span>
        <van-icon
          name="phone-o"
          color="#7C7C7D"
          size="24"
          style="padding: 0 25px"
        />
      </div>
    </div>
    <van-popup
      v-model="show"
      position="top"
      closeable
      close-icon-position="top-left"
      :style="{ height: '100%' }"
    >
      <div style="height: 100%; padding: 46px 30px; box-sizing: border-box">
        <div class="header-title">{{ cinemaInfo.name }}</div>
        <div class="tags-pop" v-for="(item, i) in cinemaInfo.services" :key="i">
          <p
            class="tag-name"
            :class="i === cinemaInfo.services.length - 2 ? 'tag-1' : ''"
          >
            {{ item.name }}
          </p>
          <p class="tag-text">{{ item.description }}</p>
        </div>
      </div>
    </van-popup>
    <div>
      <div class="film-bg" v-if="filmsList.length">
        <div
          class="bg-blur"
          :style="{ backgroundImage: 'url(' + currentFilm.poster + ')' }"
        ></div>
        <cinema-film-swiper
          :swiperOptions="swiperOptions"
          :slideTo="slideTo"
          :key="filmsList.length"
        >
          <cinema-film-swiper-item
            v-for="film in filmsList"
            :key="film.filmId"
            style="width=90px;height=130px"
          >
            <img :src="film.poster" alt="" width="90px" height="130px" />
          </cinema-film-swiper-item>
        </cinema-film-swiper>
        <van-icon
          name="play"
          color="#fff"
          size="24"
          style="transform: rotate(-90deg) translateY(-50%); left: 50%"
        />
      </div>
      <div
        class="film-info"
        v-if="currentFilm"
        @click="handleDetail(currentFilm.filmId)"
      >
        <div class="film-desc">
          <div class="col-1">
            <span>{{ currentFilm.name }}</span>
            <span class="film-grade"
              ><i>{{ currentFilm.grade }}</i
              >分</span
            >
          </div>
          <div class="col-2">
            {{ currentFilm.category }} | {{ currentFilm.runtime }}分钟 |
            {{ currentFilm.director }} |
            <span v-for="(actor, index) in currentFilm.actors" :key="index"
              >{{ actor.name }}
            </span>
          </div>
        </div>
        <van-icon
          name="arrow"
          color="#666667"
          size="12"
          style="position: absolute; right: 10px"
        />
      </div>
      <van-tabs
        animated
        :ellipsis="false"
        @click="changeIndex"
        color="#FF6C29"
        title-active-color="#FF6C29"
        line-width="80px"
        line-height="2px"
      >
        <van-tab v-for="item in dateFormat" :key="item">
          <template #title>{{ item | datefilter }}</template>
          <template #default v-if="schedules.length > 0">
            <van-cell
              class="cell-box"
              v-for="item in schedules"
              :key="item.scheduleId"
              @click="handleSchedule(item.scheduleId)"
            >
              <div class="left">
                {{ item.showAt | timeFilter }}
                <span>{{ item.endAt | timeFilter }}散场</span>
              </div>
              <div class="center">
                {{ item.filmLanguage }}{{ item.imagery }}
                <span>{{ item.hallName }}</span>
              </div>
              <div class="right">
                ￥<span>{{ item.salePrice / 100 }}</span
                >起
              </div>
              <div class="btn">购票</div>
            </van-cell>
          </template>
          <template #default v-else>
            <div
              :style="{
                height: surplusHeight,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }"
            >
              <img
                src="@/assets/cinemafilm-null.png"
                alt=""
                width="70px"
                height="70px"
                style="margin-top: 40px"
              />
              <p style="font-size: 14px; color: #bdc0c5; margin-top: 10px">
                暂无场次
              </p>
            </div>
          </template>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import http from "@/utils/http";
import obj from "@/utils/mixin";
import cinemaFilmSwiper from "@/components/cinemas/CinemaFilmSwiper.vue";
import cinemaFilmSwiperItem from "@/components/cinemas/CinemaFilmSwiperItem.vue";
import moment from "moment";
import Vue from "vue";
import { mapState, mapActions } from "vuex";
import { Dialog } from "vant";

moment.locale("zh-cn"); // 设置成中文

Vue.filter("timeFilter", (time) => {
  return moment(time * 1000).format("LT");
});

Vue.filter("datefilter", (date) => {
  const today = moment().startOf("day").unix("x"); // 今天
  const tomorrow = moment().add(1, "days").startOf("days").unix("x"); // 明天
  const afterTomorrow = moment().add(2, "days").startOf("days").unix("x"); // 后天

  // console.log(today, tomorrow, afterTomorrow);
  if (date === today) {
    return moment(date * 1000).format("今天MMMDo");
  } else if (date === tomorrow) {
    return moment(date * 1000).format("明天MMMDo");
  } else if (date === afterTomorrow) {
    return moment(date * 1000).format("后天MMMDo");
  } else {
    return moment(date * 1000).format("dddMMMDo");
  }
});

export default {
  components: {
    cinemaFilmSwiper,
    cinemaFilmSwiperItem,
  },
  mixins: [obj],
  data() {
    const vuethis = this;
    return {
      surplusHeight: "0",
      show: false,
      cinemaId: "",
      filmId: "",
      timeStamp: "",
      cinemaInfo: null,
      filmsList: [],
      currentFilm: null,
      swiperOptions: {
        slidesPerView: 3.9,
        // spaceBetween: 20,
        centeredSlides: true,
        observer: true,
        on: {
          // init: function (swiper) {
          //   // Swiper初始化了
          //   console.log('当前的slide序号是' + this.activeIndex)// 或者swiper.activeIndex，swiper与this都可指代当前swiper实例
          //   // this.emit('transitionEnd')// 在初始化时触发一次transitionEnd事件，需要先设置transitionEnd
          // },
          slideChange: function () {
            // console.log('改变了，activeIndex为' + this.activeIndex)
            vuethis.activeIndex = this.activeIndex;
          },
          slideChangeTransitionEnd: function () {
            // alert(this.activeIndex)// 切换结束时，告诉我现在是第几个slide
            vuethis.changeFilm(this.activeIndex);
          },
        },
      },
      slideTo: {
        flag: false,
        index: 0,
      },
      activeIndex: 0, // 轮播图当前下标
      schedules: [],
      dateFormat: [], // 日期转换为需要的格式
      showCinemas: [], // 日期影院相关联的接口返回的数据
    };
  },
  computed: {
    ...mapState("dataListTimeStamp", ["showDateList", "cinemaTimeStamp"]),
    ...mapState("login", ["userinfo"]),
  },
  created() {},
  mounted() {
    // console.log(this.$route)
    this.cinemaId = this.$route.params.cinemaId;
    this.filmId = this.$route.params.filmId;
    this.timeStamp = this.$route.params.timeStamp;

    this.getTimeStampCinema(this.cinemaId).then((response) => {
      // console.log(response, '影院电影时间戳')
    });

    http({
      url: `/gateway/?cinemaId=${this.cinemaId}&k=287095`,
      headers: {
        "X-Host": "mall.film-ticket.cinema.info",
      },
    }).then((response) => {
      // console.log(response.data.data.cinema)
      this.cinemaInfo = response.data.data.cinema;
    });

    http({
      url: `/gateway/?cinemaId=${this.cinemaId}&k=287095`,
      headers: {
        "X-Host": "mall.film-ticket.film.cinema-show-film",
      },
    }).then((response) => {
      // console.log(response.data.data.films)
      this.filmsList = response.data.data.films;
      this.currentFilm = response.data.data.films[this.activeIndex];
      // console.log(this.currentFilm)

      for (let i = 0; i < this.filmsList.length; i++) {
        if (this.filmsList[i].filmId === parseInt(this.filmId)) {
          if (this.$route.params.from === "filmcinemas") {
            this.changeFilm(i);
            this.slideTo = {
              flag: true,
              index: i,
            };
          } else {
            this.slideTo = {
              flag: false,
              index: 0,
            };
          }
        }
      }
    });

    this.surplusHeight = document.documentElement.clientHeight - 461 + "px";
    // onresize 事件会在窗口或框架被调整大小时发生
    window.onresize = () => {
      console.log(document.documentElement.clientHeight);
      this.surplusHeight = document.documentElement.clientHeight - 461 + "px";
    };

    this.getTimeStampCinema(this.$route.params.cinemaId).then((response) => {
      // console.log(response, '购票')
      // console.log(this.cinemaTimeStamp, 'this.cinemaTimeStamp')
      // console.log(this.cinemaTimeStamp[0].showDate, 'this.cinemaTimeStamp.showDate')
      this.dateFormat = this.modifyDate(this.cinemaTimeStamp[0].showDate);
      // console.log(this.dateFormat, '--------============')
      if (this.$route.params.filmId) {
        const newArr = response.filter(
          (item) => item.filmId === parseInt(this.$route.params.filmId)
        );
        // console.log(newArr, 'newArr')
        this.getSchedules(newArr[0].showDate[0]);
      } else {
        this.$router.replace({
          params: {
            filmId: response[0].filmId,
          },
        });
        this.getSchedules(response[0].showDate[0]);
      }
    });
  },
  methods: {
    ...mapActions("dataListTimeStamp", [
      "getTimeStampCity",
      "getTimeStampCinema",
    ]),
    handleSchedule(scheduleId) {
      if (this.userinfo) {
        this.$router.push({
          name: "schedule",
          params: {
            scheduleId: scheduleId,
            timeStamp: this.$route.params.timeStamp,
            cinemaName: this.cinemaInfo.name,
          },
        });
      } else {
        Dialog.confirm({
          message: "还未登录，请先登录账号",
        })
          .then(() => {
            // on confirm
            this.$router.push({ name: "login" });
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    changeIndex(index) {
      // console.log(index, 'index')
      this.timeStamp = this.dateFormat[index].timeStamp;
      // console.log(this.timeStamp)
      this.getSchedules(this.timeStamp);
    },
    changeFilm(index) {
      this.currentFilm = this.filmsList[index];
      const params = {
        cinemaId: this.$route.params.cinemaId,
        filmId: this.filmsList[index].filmId,
        timeStamp: this.cinemaTimeStamp[index].showDate[0],
        from: "filmcinemas",
      };

      // console.log(this.cinemaTimeStamp[index], '切换电影')
      this.dateFormat = this.modifyDate(this.cinemaTimeStamp[index].showDate);
      // console.log(this.dateFormat, 'changeFilm')
      // console.log(this.cinemaTimeStamp[index])

      if (
        this.$route.params.cinemaId !== params.cinemaId ||
        this.$route.params.filmId !== params.filmId ||
        this.$route.params.timeStamp !== params.timeStamp
      ) {
        this.$router.replace({ params }); // 修改页面路径但是不刷新页面
      }

      this.getSchedules(this.cinemaTimeStamp[index].showDate[0]);
    },
    getSchedules(timeStamp) {
      http({
        url: `/gateway/?filmId=${this.$route.params.filmId}&cinemaId=${this.cinemaId}&date=${timeStamp}&k=1223360`,
        headers: {
          "X-Host": "mall.film-ticket.schedule.list",
        },
      }).then((response) => {
        console.log(response.data.data, "getSchedules");
        this.schedules =
          response.data.data === null ? [] : response.data.data.schedules;
        localStorage.setItem("schedules", JSON.stringify(this.schedules));
      });
    },
    modifyDate(arr) {
      console.log(arr);
      if (arr.length > 1) {
        arr.sort((a, b) => {
          return b > a ? -1 : 1;
        });
      }
      // console.log(arr)
      return arr;
    },
    showPopup() {
      this.show = true;
    },
    handleDetail(filmId) {
      this.$router.push({
        name: "detail",
        params: {
          filmId: filmId,
          from: "cinemafilm",
        },
      });
    },
    handleBack() {
      this.$router.back();
    },
  },
};
</script>

<style scoped lang="scss">
.swiper-slide {
  background-color: rgba(0, 0, 0, 0);
}

.van-hairline--bottom::after {
  border-bottom-width: 0;
}

::v-deep .van-tabs__wrap {
  position: sticky;
  top: 124px;
  z-index: 2;
  border-bottom: 1px solid #f7f8f9;
}

.header-title {
  font-size: 17px;
  color: #191a1b;
  height: 44px;
  line-height: 44px;
  background: #fff;
  width: max-content;
  max-width: calc(100% - 100px);
  margin: 0 auto;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tags {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #ffb232;
  background: #fff;
  padding: 5px 0 15px;
  border-bottom: 1px solid #f8f8f8;

  span {
    margin-right: 5px;
  }

  .tag {
    border: 1px solid #ffd898;
    border-top: none;
    border-left: none;
    padding: 0 5px 0 0;
    width: max-content;
  }

  .tag-1 {
    border: 1px solid #ffd898;
    border-top: none;
    border-right: none;
    padding: 0 0 0 5px;
    margin-right: 8px;
  }
}

.tags-pop {
  font-size: 10px;
  color: #ffb232;
  background: #fff;
  padding: 5px 0 15px;

  span {
    margin-right: 5px;
  }

  .tag-name {
    border: 1px solid #ffd898;
    border-top: none;
    border-left: none;
    padding: 0 5px 0 0;
    width: max-content;
    float: left;
  }

  .tag-text {
    color: #797d82;
    padding-left: 70px;
  }

  .tag-1 {
    border: 1px solid #ffd898;
    border-top: none;
    border-right: none;
    padding: 0 0 0 5px;
    margin-right: 8px;
  }
}

.address {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding-left: 17px;
  height: 50px;

  span {
    flex: 1;
    font-size: 14px;
    padding: 0 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.film-bg {
  height: 160px;
  padding: 15px 0;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;

  .bg-blur {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    // background-position: center;
    // background-size: cover;
    filter: blur(25px);
    overflow: hidden;
  }
}

.film-info {
  background: #fff;
  border-bottom: 1px solid #f7f8f9;
  padding: 15px 0;
  display: flex;
  align-items: center;
  position: sticky;
  top: 46px;
  z-index: 2;

  .film-desc {
    width: 100%;
    padding: 0 45px;
    box-sizing: border-box;

    .col-1 {
      font-size: 15px;
      text-align: center;
      margin-bottom: 10px;

      .film-grade {
        font-size: 12px;
        color: #ffb232;
        margin-left: 5px;

        i {
          font-size: 16px;
        }
      }
    }

    .col-2 {
      color: #797d82;
      font-size: 13px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.data {
  background: #fff;
  height: 49px;
  line-height: 49px;
  color: #ff5f16;
  padding-left: 20px;
  font-size: 14px;
  border: 1px solid #f8f8f8;

  span {
    display: inline-block;
    height: 48px;
    border-bottom: 2px solid #ff5f16;
  }
}

.cell-box > div {
  display: flex;
  align-items: center;

  .left {
    width: 84px;
    font-size: 15px;
    display: flex;
    flex-direction: column;

    span {
      font-size: 13px;
      color: #797d82;
    }
  }

  .center {
    flex: 1;
    display: flex;
    flex-direction: column;
    width: 135px;

    span {
      font-size: 13px;
      color: #797d82;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .right {
    width: 74px;
    font-size: 12px;
    color: #ff5f16;

    span {
      font-size: 15px;
    }
  }
}

.btn {
  width: 50px;
  height: 25px;
  line-height: 25px;
  font-size: 14px;
  color: #ff5f16;
  border: 1px solid #ff5f16;
  border-radius: 3px;
  text-align: center;
}

.btn:active {
  color: #fff;
  background-color: #ff5f16;
}
</style>
